package com.eascs.admin.o2o.loan.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.loan.form.LoanTimeSearchForm;
import com.eascs.admin.o2o.loan.service.LoanTimeService;
import com.eascs.app.dao.PageResult;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.type.SystemModule;

@Controller
@RequestMapping("/loanTime")
public class LoanTimeController extends BaseMasterViewController {

	@Reference
	SysOrgService sysOrgService;
	@Autowired
	private LoanTimeService loanTimeService;
	@Autowired
	private BaseUtils baseUtils;

	@RequestMapping(value = "/list")
	public String search(LoanTimeSearchForm form) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "DKSQSXCX");
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		form.setPageSize(BaseUtils.PAGE_SIZE);
		PageResult<Object[]> pageResult = loanTimeService.findByPage(form, "search");
		String[] titles = { "贷款单号", "省区", "信贷经理", "征信准入开始时间", "实际放款时间", "贷款申请用时/(天)" };
		String reporto2ourl = "/loanTime/download";
		StringBuffer pageUrl = new StringBuffer("/loanTime/list");
		if (form != null) {
			String billCode = form.getBillCode() == null ? "" : form.getBillCode();
			String provinceName = form.getProvinceName() == null ? "" : form.getProvinceName();
			String operatorName = form.getOperatorName() == null ? "" : form.getOperatorName();
			String startTime = form.getStartTime() == null ? "" : form.getStartTime().toString();
			String endTime = form.getEndTime() == null ? "" : form.getEndTime().toString();
			String loanUseStartTime = form.getLoanUseStartTime() == null ? "" : form.getLoanUseStartTime() + "";
			String loanUseEndTime = form.getLoanUseEndTime() == null ? "" : form.getLoanUseEndTime() + "";
			pageUrl.append("?billCode=" + billCode);
			pageUrl.append("&provinceName=" + provinceName);
			pageUrl.append("&operatorName=" + operatorName);
			pageUrl.append("&startTime=" + startTime);
			pageUrl.append("&endTime=" + endTime);
			pageUrl.append("&loanUseStartTime=" + loanUseStartTime);
			pageUrl.append("&loanUseEndTime=" + loanUseEndTime);
		}
		pageUrl.append("&pageIndex=");
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl.toString());
		Button[] titleButton = new Button[] {
				ButtonHelper.createRedirectButton(null, "/loanTime/detail?loanapplyNo=") };
		paginationInfo.setTitleButtons(titleButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("loanTimeForm", form);
		ViewContext.put("reporto2ourl", reporto2ourl);
		// User user = UserHolder.getUser();
		return "/loanTime/list";
	}

	/**
	 * 贷款时效导出（已优化）
	 * @param form
	 * @param httpServletResponse
	 * @param request
	 */
	@RequestMapping("/download")
	public void dowanload(LoanTimeSearchForm form, HttpServletResponse httpServletResponse,
			HttpServletRequest request) {
		form.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = loanTimeService.findByPage(form, "download");
		try {
			String outfile = "贷款申请时效.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(),
					LoanTimeController.class.getResourceAsStream("/excelTemplate/loanTime.xls"),
					defaultRowWriteHandler);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		}
	}

	@RequestMapping("/detail")
	public String detail(String loanapplyNo) {
		String agreeUrl = baseUtils.getApprovalAgreeUrl(loanapplyNo, null, SystemModule.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		return "/loanTime/detail";
	}
}
